<template>
  <div>
    <div class="">
      <el-button type="primary" @click="create1">创建团队</el-button>
    </div>
    <el-dialog
      width="70%"
      :title="title"
      @closed="closed"
      v-model="dialogVisible"
      align-center
      draggable
    >
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          {{ title }}
        </span>
      </template>
      <el-form :model="formdata" label-width="auto">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="团队名称" prop="name">
              <el-input v-model="formdata.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="团队创建者" prop="region">
              <el-avatar
                :size="48"
                :src="circleUrl"
                @click="dialogVisible2 = true"
              ></el-avatar>
              <span>{{ formdata.user ? formdata.user.name : "" }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="其他信息" prop="description">
              <el-input v-model="formdata.description"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="团队等级" prop="grade">
              <el-select v-model="formdata.grade">
                <el-option label="免费客户（Level 0）" :value="0"></el-option>
                <el-option label="黄金客户（Level 1）" :value="1"></el-option>
                <el-option label="铂金客户（Level 2）" :value="2"></el-option>
                <el-option label="钻石客户（Level 3）" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否官方创建" prop="isadmin">
              <el-select v-model="formdata.isadmin" :disabled="!!tenant_id">
                <el-option label="是" :value="false"></el-option>
                <el-option label="否" :value="true"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="显示非学员排行" prop="isranking">
              <el-select v-model="formdata.isranking">
                <el-option label="显示" :value="false"></el-option>
                <el-option label="不显示" :value="true"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="管理员显示测评记录" prop="isadminshowquestion">
              <el-select v-model="formdata.isadminshowquestion">
                <el-option label="不显示" :value="false"></el-option>
                <el-option label="显示" :value="true"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="管理员显示比赛记录" prop="isadminshowactivity">
              <el-select v-model="formdata.isadminshowactivity">
                <el-option label="不显示" :value="false"></el-option>
                <el-option label="显示" :value="true"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设置主题色" prop="color">
              <el-select v-model="formdata.color">
                <el-option label="橙色" value="-cheng"></el-option>
                <el-option label="红色" value="red"></el-option>
                <el-option label="绿色" value="green"></el-option>
                <el-option label="蓝色" value="blue"></el-option>
                <el-option label="黄色" value="yellow"></el-option>
                <el-option label="紫色" value="purple"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="团队公告">
              <el-input
                type="textarea"
                :rows="3"
                v-model="formdata.info"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="导航菜单隐藏" prop="disabledNav">
              <el-checkbox-group v-model="formdata.other!.disabledNav">
                <el-checkbox-button value="首页" size="default"
                  >首页</el-checkbox-button
                >
                <el-checkbox-button value="题库" size="default"
                  >题库</el-checkbox-button
                >
                <el-checkbox-button value="题单" size="default"
                  >题单</el-checkbox-button
                >
                <el-checkbox-button value="任务" size="default"
                  >任务</el-checkbox-button
                >
                <el-checkbox-button value="比赛" size="default"
                  >比赛</el-checkbox-button
                >
                <el-checkbox-button value="评测" size="default"
                  >评测</el-checkbox-button
                >
                <el-checkbox-button value="云课堂" size="default"
                  >云课堂</el-checkbox-button
                >
                <el-checkbox-button value="管理" size="default"
                  >管理</el-checkbox-button
                >
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="个人中心隐藏" prop="disabledNav">
              <el-checkbox-group v-model="formdata.other!.disabledUserMenu">
                <el-checkbox-button value="个人中心" size="default"
                  >个人中心</el-checkbox-button
                >
                <el-checkbox-button value="管理我的题目" size="default"
                  >管理我的题目</el-checkbox-button
                >
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="Saas域名" prop="teamkey">
              <el-input v-model="formdata.teamkey"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="RemoteJudge" prop="showRemotejudge">
              <el-switch
                v-model="formdata.other!.showRemotejudge"
                inline-prompt
                active-text="显示"
                inactive-text="隐藏"
                style="
                  --el-switch-on-color: #13ce66;
                  --el-switch-off-color: #ff4949;
                "
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 上传登录背景图 -->
            <el-form-item label="Saas登录背景" prop="loginBgUrl">
              <el-upload
                action="/"
                :show-file-list="false"
                accept=".png,.svg,.jpg"
                :http-request="requestLoginBgImg"
                class="avatar-uploader"
              >
                <img
                  v-if="formdata?.other?.loginBgUrl"
                  :src="formdata?.other?.loginBgUrl"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
              <el-button
                v-if="formdata?.other?.loginBgUrl"
                class="margin-left10"
                type="danger"
                size="default"
                :icon="Delete"
                circle
                @click="delSaasLoginBgUrl"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="SaasLogo" prop="type">
              <el-upload
                action="/"
                accept=".png,.svg,.jpg"
                :show-file-list="false"
                :http-request="requestSaasLogo"
                class="avatar-uploader"
              >
                <img
                  v-if="formdata?.other?.saasTeamLogo"
                  :src="formdata?.other?.saasTeamLogo"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
              <el-button
                v-if="formdata?.other?.saasTeamLogo"
                class="margin-left10"
                type="danger"
                size="default"
                :icon="Delete"
                circle
                @click="delSaasTeamLogo"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="logo(OJ)" prop="icon">
              <el-upload
                action="/"
                accept=".png,.svg,.jpg"
                :http-request="request"
                class="avatar-uploader"
              >
                <img v-if="formdata.icon" :src="formdata.icon" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon> </el-upload
              >&nbsp;
              <el-button
                v-if="formdata.icon"
                class="margin-left10"
                type="danger"
                :icon="Delete"
                circle
                @click="delIcon"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-form-item label="AI思路提示" prop="ideaTips">
            <el-switch
              size=""
              v-model="formdata.other!.ideaTips"
              inline-prompt
              active-text="显示"
              inactive-text="隐藏"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="AI代码协助" prop="codeHelp">
            <el-switch
              size=""
              v-model="formdata.other!.codeHelp"
              inline-prompt
              active-text="显示"
              inactive-text="隐藏"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="AI分析比赛" prop="activitySummarize">
            <el-switch
              size=""
              v-model="formdata.other!.activitySummarize"
              inline-prompt
              active-text="显示"
              inactive-text="隐藏"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="AI分析比赛成员" prop="activityUserSummarize">
            <el-switch
              size=""
              v-model="formdata.other!.activityUserSummarize"
              inline-prompt
              active-text="显示"
              inactive-text="隐藏"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
            >
            </el-switch>
          </el-form-item>
        </el-row>
        <el-row :gutter="10" v-if="!tenant_id">
          <el-col :span="24">
            <el-form-item>
              <el-alert
                type="warning"
                show-icon
                :closable="false"
                title="团队屏蔽题库"
                description=""
              >
                <template #default>
                  <el-text type="warning"
                    >勾选下方各个题目分组即表示对该团队成员屏蔽所选题目分组</el-text
                  >
                  <el-text tag="b" type="danger">
                    (所勾选的分组，其对应的题目不可见!)
                  </el-text>
                </template>
              </el-alert>
            </el-form-item>
          </el-col>
          <el-form-item label="难度" prop="questiondifficulty">
            <el-checkbox-group v-model="formdata.questiondifficulty">
              <el-checkbox-button
                v-for="(item, index) in DATAdifficulty"
                :key="item"
                :label="item"
                :value="index"
                size="default"
              >
              </el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="分组" prop="questionlable">
            <el-select-v2
              style="width: 200px"
              v-model="formdata.questionlable"
              clearable
              :options="questionGroup"
              filterable
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="可输入名称查询"
            >
            </el-select-v2>
          </el-form-item>
        </el-row>
      </el-form>
      <div style="display: flex; justify-content: flex-end">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
      <el-dialog width="950px" v-model="dialogVisible2">
        <template #header>
          <span class="icon-text el-dialog__header-title">
            <el-icon class="text-primary">
              <Guide />
            </el-icon>
            选择用户
          </span>
        </template>
        <User v-bind="{ userhandleCurrentChange, tablekey }"></User>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Delete, Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { computed, inject, onMounted, reactive, ref, toRefs, watch } from "vue";
import { useStore } from "vuex";
import {
  asyncadmincreatorupdateteam,
  asyncchangeteamcoursegroup,
  asyncselectlabel,
} from "../../../api";
import { DATAdifficulty } from "../../../index/data/data";
import { Storekey } from "../../../interface";
import study from "../../../mysql_interface/studycodemodel";
import { questionGroupType } from "../../../util/questionPermissions";
import updateoss from "../../../util/updateoss";
import User from "../User/index.vue";
// 码客行
const tenant_id = inject<string | undefined>("tenant_id", undefined);

const p = defineProps<{
  ID?: number;
  team: study.Iteam;
  closed: () => void;
  create: () => void;
}>();

const store = useStore(Storekey);
const getuser = computed(() => {
  return store.state.user || {};
});

const questionGroup = ref<{ value?: number; label?: string }[]>([]);

const formdata = reactive<study.Iteam>({ other: {}, ...p.team, ID: p.ID });
const dialogVisible = ref(false);
const dialogVisible2 = ref(false);
const title = computed(() => {
  if (p.ID) {
    return `修改团队-${formdata.name}-${formdata.ID}`;
  }
  return `创建团队-${formdata.ID || ""}`;
});

function userhandleCurrentChange(data: study.Iuser) {
  Object.assign(userinfo, toRefs(data));
  dialogVisible2.value = false;
}
const username = ref();

const userinfo = reactive<study.Iuser>({});
const circleUrl = computed(() => {
  if (formdata.user) return formdata.user.headportrait;
  return "";
});

onMounted(async () => {
  if (tenant_id) {
    Object.assign(userinfo, getuser.value);
  }
  // 获取分组
  const { rows, count } = await asyncselectlabel({
    type: questionGroupType,
    _limit: 9999,
    tenant_id,
  });
  questionGroup.value = rows.map((e) => {
    return { value: e.ID, label: e.name };
  });
});

watch(
  () => userinfo.ID,
  () => {
    console.log("码客行=>", tenant_id);
    console.log("选中了要添加进入团队的成员=>", userinfo, getuser.value);
    formdata.userid = userinfo.ID;
    Object.assign(formdata, {
      user: {
        headportrait: userinfo.headportrait,
        name: userinfo.name,
      },
    });
  }
);

watch(
  () => p.ID,
  async () => {
    Object.assign(formdata, {
      ...p.team,
      ID: p.ID,
      questiondifficulty: p.team?.questiondifficulty ?? [],
    });
    if (typeof p.ID === "number") {
      dialogVisible.value = true;
    }
    console.log("watch p.ID=>", formdata.ID, formdata);
  }
);

// 监听 team name 变化，动态更新公告内容
// watch(() => formdata.name, (newName) => {
//   if (newName) {
//     formdata.info = `欢迎来到${newName}`;
//   }
// });

async function submit() {
  try {
    console.log(
      "Object.assign(p.team, formdata)",
      Object.assign(p.team, formdata, {
        questionlable: [...new Set(formdata?.questionlable?.flat())],
      })
    );

    const ret = await asyncadmincreatorupdateteam(
      Object.assign(p.team, formdata)
    );
    if (!p.ID && formdata.teamkey) {
      // 设置默认代理商课包
      const teamID = ret.ID;
      const coursegroupids = [31, 21, 22, 23, 24, 46, 59];
      const pAll = coursegroupids.map(async (id) => {
        return asyncchangeteamcoursegroup({
          teamid: teamID,
          coursegroupid: id,
        });
      });
      await Promise.all(pAll);
    }
    ElMessage.success(title.value + "成功");
    dialogVisible.value = false;
  } catch (e: any) {
    ElMessage.error(e);
  }
}
async function create1() {
  p.create();
  dialogVisible.value = true;
  // if (!formdata.info) {
  //   formdata.info = `欢迎来到${formdata.name || "您的团队"}`; // 设置默认值
  // }
}

const tablekey: Array<keyof study.Iuser> = ["name", "ID"];

async function request(file: { file: File }) {
  const { name } = await updateoss([file.file]);
  formdata.icon = `https://cdn.hterobot.com/${name}`;
}
// 删除团队 icon
function delIcon() {
  formdata.icon = "";
}

// 登录背景图片上传
async function requestLoginBgImg(file: { file: File }) {
  const { name } = await updateoss([file.file]);
  // 初始值
  if (!formdata.other) {
    formdata.other = {
      loginBgUrl: `https://cdn.hterobot.com/${name}`,
    };
  } else {
    formdata.other.loginBgUrl = `https://cdn.hterobot.com/${name}`;
  }
  Object.assign(p.team.other || {}, formdata.other);
}
// saas团队logo上传
async function requestSaasLogo(file: { file: File }) {
  const { name } = await updateoss([file.file]);
  formdata.other!.saasTeamLogo = `https://cdn.hterobot.com/${name}`;
}
// 删除团队 icon
function delSaasTeamLogo() {
  formdata.other!.saasTeamLogo = "";
}
// 删除团队 icon
function delSaasLoginBgUrl() {
  formdata.other!.loginBgUrl = "";
}
</script>

<style scoped>
.avatar {
  /* height: 90px; */
  max-width: 200px;
}

/* .avatar-uploader-icon {
  height: 64px;
  min-width: 64px;
  font-size: 64px;
  border: 1px solid #000;
} */
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  background-color: var(--el-fill-color-lighter);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
}
</style>
